package com.xwaf.platform.web.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class GetSmallQrCode {

	private static final Logger log = LoggerFactory.getLogger(GetSmallQrCode.class);

	public String getminiqrQr(OSSManageUtil ossUtil, String sceneStr, String accessToken) {
		log.info("进入小程序二维码生成方法");
		RestTemplate rest = new RestTemplate();
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
			log.info("url==" + url);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("scene", sceneStr);
			// param.put("page", "pages/myRecommendForm/myRecommendForm");//小程序跳转页面
			param.put("page", "");// 小程序跳转页面
			param.put("width", 200);
			param.put("auto_color", false);
			Map<String, Object> line_color = new HashMap<>();
			line_color.put("r", 0);
			line_color.put("g", 0);
			line_color.put("b", 0);
			param.put("line_color", line_color);
			log.info("调用生成微信URL接口传参:" + param);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
			HttpEntity requestEntity = new HttpEntity(param, headers);
			ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class,
					new Object[0]);
			log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
			byte[] result = entity.getBody();
			inputStream = new ByteArrayInputStream(result);
			// OSS 上传
			String str = ossUtil.uploadFile(inputStream, inputStream.available(), System.currentTimeMillis() + ".jpg");
			return str;
		} catch (Exception e) {
			log.error("调用小程序生成微信永久小程序码URL接口异常", e);
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
